<template>
  <view class="container">
    <u-form :model="form" ref="uForm">
      <u-form-item label="标题" prop="title" :required="true">
        <u-input v-model="form.title" placeholder="请输入成果标题" />
      </u-form-item>
      
      <u-form-item label="描述" prop="description">
        <u-input
          v-model="form.description"
          type="textarea"
          placeholder="请输入成果描述"
          height="150"
        />
      </u-form-item>
      
      <u-form-item label="分类" prop="categoryId">
        <u-input
          v-model="categoryName"
          placeholder="请选择分类"
          disabled
          @click="showCategoryPicker = true"
        />
      </u-form-item>
      
      <u-form-item label="标签" prop="tags">
        <u-input
          v-model="tagsText"
          placeholder="请输入标签，多个标签用逗号分隔"
        />
      </u-form-item>
      
      <u-form-item label="完成日期" prop="completionDate">
        <u-input
          v-model="form.completionDate"
          placeholder="请选择完成日期"
          disabled
          @click="showDatePicker = true"
        />
      </u-form-item>
      
      <u-form-item label="是否公开" prop="isPublic">
        <u-switch v-model="form.isPublic" :active-value="1" :inactive-value="0"></u-switch>
      </u-form-item>
      
      <view class="form-actions">
        <u-button type="primary" @click="submitForm">保存</u-button>
        <u-button @click="goBack">取消</u-button>
      </view>
    </u-form>
    
    <u-picker
      mode="selector"
      v-model="showCategoryPicker"
      :columns="[categoryOptions]"
      @confirm="onCategoryConfirm"
    ></u-picker>
    
    <u-picker
      mode="time"
      v-model="showDatePicker"
      :params="datePickerParams"
      @confirm="onDateConfirm"
    ></u-picker>
  </view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { formatDate } from '@/utils/date'

export default {
  data() {
    return {
      id: null,
      isEdit: false,
      form: {
        title: '',
        description: '',
        categoryId: -1,
        tags: [],
        completionDate: formatDate(new Date(), 'YYYY-MM-DD'),
        isPublic: 1
      },
      categoryName: '未分类',
      tagsText: '',
      categoryOptions: [],
      showCategoryPicker: false,
      showDatePicker: false,
      datePickerParams: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false
      }
    }
  },
  computed: {
    ...mapGetters({
      currentAchievement: 'achievement/currentAchievement',
      achievementCategories: 'category/achievementCategories'
    })
  },
  onLoad(options) {
    if (options.id) {
      this.id = options.id
      this.isEdit = true
    }
    
    this.initData()
  },
  methods: {
    ...mapActions('achievement', [
      'getAchievementDetail',
      'createAchievement',
      'updateAchievement'
    ]),
    ...mapActions('category', ['getCategoryList']),
    formatDate,
    
    // 初始化数据
    async initData() {
      uni.showLoading({
        title: '加载中...'
      })
      
      try {
        // 获取分类列表
        await this.getCategoryList(3) // 3表示成果分类
        this.initCategoryOptions()
        
        // 如果是编辑模式，加载成果详情
        if (this.isEdit && this.id) {
          await this.getAchievementDetail(this.id)
          this.fillFormData()
        }
      } catch (error) {
        console.error('加载数据失败', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 初始化分类选项
    initCategoryOptions() {
      this.categoryOptions = [
        { value: -1, label: '未分类' }
      ]
      
      if (this.achievementCategories && this.achievementCategories.length > 0) {
        this.achievementCategories.forEach(category => {
          this.categoryOptions.push({
            value: category.id,
            label: category.name
          })
        })
      }
    },
    
    // 填充表单数据
    fillFormData() {
      if (!this.currentAchievement) return
      
      // 填充基本信息
      this.form.title = this.currentAchievement.title || ''
      this.form.description = this.currentAchievement.description || ''
      this.form.categoryId = this.currentAchievement.categoryId || -1
      this.form.completionDate = formatDate(this.currentAchievement.completionDate, 'YYYY-MM-DD') || formatDate(new Date(), 'YYYY-MM-DD')
      this.form.isPublic = this.currentAchievement.isPublic || 0
      
      // 处理标签
      if (this.currentAchievement.tags) {
        try {
          const tags = typeof this.currentAchievement.tags === 'string' 
            ? JSON.parse(this.currentAchievement.tags) 
            : this.currentAchievement.tags
          
          this.form.tags = Array.isArray(tags) ? tags : []
          this.tagsText = this.form.tags.join(',')
        } catch (error) {
          this.form.tags = []
          this.tagsText = ''
        }
      }
      
      // 设置分类名称
      this.updateCategoryName()
    },
    
    // 更新分类名称
    updateCategoryName() {
      const category = this.categoryOptions.find(item => item.value === this.form.categoryId)
      this.categoryName = category ? category.label : '未分类'
    },
    
    // 分类确认
    onCategoryConfirm(e) {
      this.form.categoryId = e.value[0].value
      this.categoryName = e.value[0].label
    },
    
    // 日期确认
    onDateConfirm(e) {
      this.form.completionDate = `${e.year}-${e.month}-${e.day}`
    },
    
    // 处理标签
    processTags() {
      if (!this.tagsText) {
        this.form.tags = []
        return
      }
      
      // 将标签文本转换为数组
      const tags = this.tagsText.split(',').map(tag => tag.trim()).filter(tag => tag)
      this.form.tags = [...new Set(tags)] // 去重
    },
    
    // 提交表单
    async submitForm() {
      // 简单验证标题是否为空
      if (!this.form.title || this.form.title.trim() === '') {
        uni.showToast({
          title: '请输入成果标题',
          icon: 'none'
        })
        return
      }
      
      // 处理标签
      this.processTags()
      
      uni.showLoading({
        title: this.isEdit ? '更新中...' : '创建中...'
      })
      
      try {
        const data = {
          ...this.form,
          tags: JSON.stringify(this.form.tags)
        }
        
        if (this.isEdit) {
          data.id = this.id
          await this.updateAchievement(data)
        } else {
          await this.createAchievement(data)
        }
        
        uni.hideLoading()
        
        uni.showToast({
          title: this.isEdit ? '更新成功' : '创建成功',
          icon: 'success',
          duration: 1500,
          success: () => {
            // 使用 setTimeout 确保 toast 显示完成后再跳转
            setTimeout(() => {
              console.log('准备跳转到成果列表页面')
              uni.reLaunch({
                url: '/pages/achievement/index',
                success: () => {
                  console.log('跳转成功')
                },
                fail: (err) => {
                  console.error('跳转失败', err)
                }
              })
            }, 1600)
          }
        })
      } catch (error) {
        console.error(this.isEdit ? '更新失败' : '创建失败', error)
        uni.hideLoading()
        uni.showToast({
          title: this.isEdit ? '更新失败' : '创建失败',
          icon: 'none'
        })
      }
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
}

.form-actions {
  margin-top: 50rpx;
  display: flex;
  justify-content: space-between;
}

.u-button {
  width: 45%;
}
</style> 